<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>SpringMVC | C·辰</title><meta name="author" content="辰"><meta name="copyright" content="辰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="SpringMVC">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC">
<meta property="og:url" content="http://example.com/2023/05/02/SpringMVC/index.html">
<meta property="og:site_name" content="C·辰">
<meta property="og:description" content="SpringMVC">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/springmvc.webp">
<meta property="article:published_time" content="2023-05-02T14:22:22.000Z">
<meta property="article:modified_time" content="2023-08-24T12:23:44.330Z">
<meta property="article:author" content="辰">
<meta property="article:tag" content="SpringMVC">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/springmvc.webp"><link rel="shortcut icon" href="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Bell.ico"><link rel="canonical" href="http://example.com/2023/05/02/SpringMVC/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'SpringMVC',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-24 20:23:44'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/springmvc.webp')"><nav id="nav"><span id="blog-info"><a href="/" title="C·辰"><span class="site-name">C·辰</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">SpringMVC</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-02T14:22:22.000Z" title="发表于 2023-05-02 22:22:22">2023-05-02</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-24T12:23:44.330Z" title="更新于 2023-08-24 20:23:44">2023-08-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/SSM%E6%A1%86%E6%9E%B6/">SSM框架</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">7.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>35分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="SpringMVC"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="SpringMVC"><a href="#SpringMVC" class="headerlink" title="SpringMVC"></a>SpringMVC</h1><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230721214602324.png" alt="image-20230721214602324"></p>
<br/>

<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230607181409242.png" alt=" "></p>
<ul>
<li>MVC : 模型(dao,service)	视图(jsp)	控制器(Servlet)</li>
</ul>
<br/>

<br/>



<p>核心</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--处理器映射器--&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--处理器适配器--&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--视图解析器--&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="HelloSpringMVC"><a href="#HelloSpringMVC" class="headerlink" title="HelloSpringMVC"></a>HelloSpringMVC</h1><p>1.新建一个Moudle,添加web框架支持！</p>
<p>2.确定导入了SpringMVC的依赖！</p>
<blockquote>
<p>项目结构 –&gt;  工件  –&gt;  在WEB-INF目录下创建lib文件夹 与class同级  –&gt; 点击 + 选择库文件  –&gt;  全选导入</p>
</blockquote>
<p>3.配置web.xml,注册DispatcherServlet</p>
<br/>

<br/>

<h2 id="原生流程"><a href="#原生流程" class="headerlink" title="原生流程"></a>原生流程</h2><h3 id="1、web-xml"><a href="#1、web-xml" class="headerlink" title="1、web.xml"></a>1、web.xml</h3><ul>
<li><strong>配置DispatchServlet</strong></li>
<li><strong>请求</strong></li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">web-app</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">version</span>=<span class="string">&quot;4.0&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--1.注册Servlet--&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置DispatchServlet:这个是SpringMVC的核心：请求分发器，前端控制器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>springmvc<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- DispatchServlet 要绑定Spring的配置文件--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--配置文件--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>classpath:springmvc-servlet.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--启动级别：1（服务器一启动则同一起启动）--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="name">load-on-startup</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">        在SpringMVC中 ，/  和 /*</span></span><br><span class="line"><span class="comment">        /  ：只匹配所有的请求，不会去匹配jsp页面</span></span><br><span class="line"><span class="comment">        /* ：匹配所有的请求，包括jsp页面（如请求为：index.jsp,会继续走视图解析器，无限拼接请求字符index.jsp.index.jsp）</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>springmvc<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<h3 id="2、springmvc-servlet-xml"><a href="#2、springmvc-servlet-xml" class="headerlink" title="2、springmvc-servlet.xml"></a>2、springmvc-servlet.xml</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="string"><span class="tag">        https://www.springframework.org/schema/beans/spring-beans.xsd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--处理器映射器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--处理器适配器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--视图解析器  (将来：模板引擎 Thymeleaf  Freemarker) </span></span><br><span class="line"><span class="comment">          1.获取ModeLAndview的数据</span></span><br><span class="line"><span class="comment">          2.解析ModelAndview的视图名字</span></span><br><span class="line"><span class="comment">          3.拼接视图名字，找到对应的视图 wEB-INF/5sp/helLo.jsp</span></span><br><span class="line"><span class="comment">          4.将数据渲染到这个视图上</span></span><br><span class="line"><span class="comment">	--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--前缀--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;prefix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;/WEB-INF/jsp/&quot;</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--后缀--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;suffix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;.jsp&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230608011342167.png" alt="image-20230608011342167"></p>
<br/>

<h3 id="3、类Controller"><a href="#3、类Controller" class="headerlink" title="3、类Controller"></a>3、类Controller</h3><ul>
<li><strong>实现Controller接口</strong>，说明这就是一个控制器了</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloController</span> <span class="keyword">implements</span> <span class="title class_">Controller</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> ModelAndView <span class="title function_">handleRequest</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">ModelAndView</span> <span class="variable">modelAndView</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ModelAndView</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//调用业务层</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//封装对象，放ModeLAndview中。ModeL</span></span><br><span class="line">        modelAndView.addObject(<span class="string">&quot;键&quot;</span>,值);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//视图跳转,封装要跳转的视图，放在ModeLAndview中</span></span><br><span class="line">        modelAndView.setViewName(<span class="string">&quot;ViewName&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> modelAndView;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<p>4、配置请求的bean</p>
<ul>
<li>写完毕后，去springmvc-servlet.xml配置文件中注册请求的bean；name &#x2F; id 对应请求路径，class对应处理请求的类</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--BeanNameUrlHandlerMapping:bean--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">&quot;/请求路径&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.chen.controller.HelloController&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h1 id="简要分析执行流程"><a href="#简要分析执行流程" class="headerlink" title="简要分析执行流程"></a>简要分析执行流程</h1><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230607234544202.png" alt="image-20230607234544202"></p>
<ul>
<li><strong>实现虚线</strong></li>
</ul>
<br/>

<p>1.<strong>DispatcherServlet表示前置控器</strong>，是整个SpringMVC的控制中心。<strong>用户发出请l求DispatcherServlet接收请求并拦截请求。</strong></p>
<ul>
<li>假设请求的url为：<a target="_blank" rel="noopener" href="http://localhost:8080/SpringMVC/hello">http://localhost:8080/SpringMVC/hello</a></li>
<li><strong>如上url拆分成三部分</strong>：</li>
<li><a target="_blank" rel="noopener" href="http://localhost:8080/">http://localhost:8080</a>  ：服务器域名</li>
<li>SpringMVC  ：部署在服务器上的web站点</li>
<li>hello  ：表示控制器</li>
<li>如上url表示为：请求位于服务器localhost:8080上的Spring MVC站点的hello控制器。</li>
</ul>
<br/>

<p>2.HandlerMapping为处理器映射。DispatcherServleti 调用 HandlerMapping，HandlerMapping根据请求url查找Handler。</p>
<p>3.HandlerExecution 表示具体的Handler,其主要作用是<strong>根据url查找控制器</strong>，如上url被查找控制器为：hello。</p>
<p>4.HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等。</p>
<p>5.HandlerAdapter表示处理器适配器，其按照特定的规则去执行Handler。</p>
<p>6.Handleri让具体的Controller执行。</p>
<p>7.Controller将具体的执行信息返回给HandlerAdapter,如ModelAndView。</p>
<p>8.HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet。</p>
<p>9.DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名。</p>
<p>10.视图解析器将解析的逻辑视图名传给DispatcherServlet</p>
<p>11.DispatcherServlet根据视图解析器解析的视图结果，调用具体的视图。</p>
<p>12.最终视图呈现给用户。</p>
<br/>



<br/>

<br/>

<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h1><h2 id="依赖"><a href="#依赖" class="headerlink" title="依赖"></a>依赖</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>junit<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.12<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-webmvc<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>5.2.9.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.5<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet.jsp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jsp-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.2.1-b03<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jstl<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- Jackson --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jackson-databind<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.15.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h2 id="注解"><a href="#注解" class="headerlink" title="注解"></a>注解</h2><h3 id="Controller"><a href="#Controller" class="headerlink" title="@Controller"></a><strong>@Controller</strong></h3><ul>
<li>@Control1er注解的 类 会自动添加到spring上下文中  –  走视图层  – 隶属于@Component组件</li>
</ul>
<br/>

<h3 id="RestController"><a href="#RestController" class="headerlink" title="@RestController"></a><strong>@RestController</strong></h3><ul>
<li>前后端分离 – 当前 <strong>类</strong> 不走视图解析器 – 配置实现返回字字符串</li>
</ul>
<br/>

<h3 id="ResponseBody"><a href="#ResponseBody" class="headerlink" title="@ResponseBody"></a><strong>@ResponseBody</strong></h3><ul>
<li>前后端分离 – 当前 <strong>方法</strong> 不走视图解析器 – 配置实现返回字字符串</li>
</ul>
<br/>

<br/>

<h3 id="RequestMapping"><a href="#RequestMapping" class="headerlink" title="@RequestMapping"></a><strong>@RequestMapping</strong></h3><ul>
<li>映射访问路径  – （置于类上+方法上 &#x3D;&#x3D;父子组件路径)  – 方法上–单路径</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/路径&quot;)</span></span><br><span class="line"><span class="meta">@RequestMapping(value = &quot;路径&quot;, method = RequestMethod.POST )</span></span><br><span class="line">	<span class="comment">//根据请求方法实现路径映射注解替换  ==》 RequestMapping(name=&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;,method = RequestMethod.方法)</span></span><br><span class="line">     <span class="meta">@GetMapping</span>	-----  <span class="meta">@GetMapping(&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;)</span></span><br><span class="line">     <span class="meta">@PostMapping</span></span><br><span class="line">     <span class="meta">@PutMapping</span></span><br><span class="line">     <span class="meta">@DeleteMapping</span></span><br><span class="line">     <span class="meta">@PatchMapping</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h3 id="PathVariable"><a href="#PathVariable" class="headerlink" title="@PathVariable"></a><strong>@PathVariable</strong></h3><ul>
<li><strong>Restful风格</strong>  – 获取路径上的变量</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;,method = RequestMethod.GET)</span><span class="comment">//方法上</span></span><br><span class="line"></span><br><span class="line">(<span class="meta">@PathVariable(&quot;a&quot;)</span> <span class="type">int</span> a,<span class="meta">@PathVariable(&quot;b&quot;)</span> <span class="type">int</span> b)	<span class="comment">//参数</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h3 id="RequestParam"><a href="#RequestParam" class="headerlink" title="@RequestParam"></a><strong>@RequestParam</strong></h3><ul>
<li>接收数据  – url请求上携带的数据 – <strong>映射请求参数</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestParam(&quot;url中参数名&quot;)</span> String name</span><br></pre></td></tr></table></figure>

<ul>
<li>如果不传值，<strong>设置默认值</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestParam(required = false,defaultValue = &quot;1&quot;)</span> Integer pageNo</span><br></pre></td></tr></table></figure>



<br/>

<br/>

<h3 id="RequestBody"><a href="#RequestBody" class="headerlink" title="@RequestBody"></a><strong>@RequestBody</strong></h3><p><strong>请求传递的是json</strong></p>
<p> 从请求体中，获取数据，转为形参的对象</p>
<p>1、前端是json格式的数据,例如{id:1001,name:”Lisi”}</p>
<p>2、后端控制器方法，使用java对象接收参数，加入@RequestBody</p>
<p>3、服务器接收json转为对象，需要在对象类型的形参前面加入@RequestBody</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@PostMapping(&quot;/user/json&quot;)</span></span><br><span class="line"><span class="keyword">public</span> User <span class="title function_">addUserJsonUser</span><span class="params">(<span class="meta">@RequestBody</span> User user)</span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h3 id="RequestHeader"><a href="#RequestHeader" class="headerlink" title="@RequestHeader"></a>@RequestHeader</h3><p>从<strong>请求头</strong>里面获取数据</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> RespResult <span class="title function_">userCenter</span><span class="params">(<span class="meta">@RequestHeader(&quot;uid&quot;)</span> Integer uid)</span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="注解开发【-】"><a href="#注解开发【-】" class="headerlink" title="注解开发【*】"></a>注解开发【*】</h1><h2 id="1、web-xml-1"><a href="#1、web-xml-1" class="headerlink" title="1、web.xml"></a>1、web.xml</h2><ul>
<li>注册DispatcherServlet【以下内容固定】</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">web-app</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://xmlns.jcp.org/xml/ns/javaee&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd&quot;</span></span></span><br><span class="line"><span class="tag">         <span class="attr">version</span>=<span class="string">&quot;4.0&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">     <span class="comment">&lt;!--1.注册Servlet--&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 配置DispatchServlet:SpringMVC的核心：请求分发器，前端控制器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>springmvc<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- DispatchServlet 要绑定Spring的配置文件--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!--配置文件--&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>classpath:springmvc-servlet.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--启动级别：1（服务器一启动则同一起启动）--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="name">load-on-startup</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--所有请求都会被springmvc栏截--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>springmvc<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"></span><br><span class="line">     </span><br><span class="line">    <span class="comment">&lt;!--2.配置SpringMVC乱码过滤--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>org.springframework.web.filter.CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>utf-8<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>



<br/>

<h2 id="2、springmvc-servlet-配置"><a href="#2、springmvc-servlet-配置" class="headerlink" title="2、springmvc-servlet 配置"></a>2、<strong>springmvc-servlet 配置</strong></h2><ul>
<li>【以下内容固定】<ul>
<li>自动扫描</li>
<li>资源过滤</li>
<li>处理器和映射器</li>
<li>视图解析器</li>
</ul>
</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=<span class="string">&quot;1.0&quot;</span> encoding=<span class="string">&quot;UTF-8&quot;</span>?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:context</span>=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xmlns:mvc</span>=<span class="string">&quot;http://www.springframework.org/schema/mvc&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="string"><span class="tag">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="string"><span class="tag">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="string"><span class="tag">        https://www.springframework.org/schema/context/spring-context.xsd</span></span></span><br><span class="line"><span class="string"><span class="tag">        http://www.springframework.org/schema/mvc</span></span></span><br><span class="line"><span class="string"><span class="tag">        https://www.springframework.org/schema/mvc/spring-mvc.xsd&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--自动扫描包，让指定包下的注解生效，由I0C容器统一管理--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">&quot;   packNaem    &quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!--资源过滤Spring MVC不处理静态资源  .css  .js  .html  .png--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mvc:default-servlet-handler</span> /&gt;</span></span><br><span class="line">     </span><br><span class="line">    <span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">    支持mvc注解驱动 -- 处理器和映射器</span></span><br><span class="line"><span class="comment">        在spring中一般采用@RequestMapping注解来完成映射关系</span></span><br><span class="line"><span class="comment">        要想使@RequestMapping.注解生效</span></span><br><span class="line"><span class="comment">        必须向上下文中注册DefaultAnnotationHandlerMapping</span></span><br><span class="line"><span class="comment">        和一个AnnotationMethodHandlerAdapter.实例</span></span><br><span class="line"><span class="comment">        这两个实例分别在类级别和方法级别处理。</span></span><br><span class="line"><span class="comment">        而annotation-driven,配置帮助我们自动完成上述两个实例的注入。</span></span><br><span class="line"><span class="comment">    --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mvc:annotation-driven</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!--视图解析器--&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;</span></span></span><br><span class="line"><span class="tag">          <span class="attr">id</span>=<span class="string">&quot;internalResourceviewResolver&quot;</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--前缀--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;prefix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;/WEB-INF/jsp/&quot;</span>/&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--后缀--&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;suffix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;.jsp&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<h2 id="3、创建制类"><a href="#3、创建制类" class="headerlink" title="3、创建制类"></a>3、创建制类</h2><p><strong>controller</strong></p>
<ul>
<li>@Controller  :  被spring托管</li>
</ul>
<blockquote>
<p>代表这个类spring托管，被这个注解的类所有的<strong>方法</strong>，如果**返回值是String,**并且有具体页面可以跳转，那么就会被视图解析器解析</p>
</blockquote>
<br/>

<ul>
<li><p>@RequestMapping(“&#x2F;hello”) – 映射访问路径</p>
<blockquote>
<p>类前：为下层RequestMapping添加前缀  —–  拼接，前缀为&#x2F;hello&#x2F;子</p>
<p>方法：拼接网址</p>
</blockquote>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//@Control1er注解的类会自动添加到spring上下文中</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//添加前缀--（如果在类上添加则为上层地址，类中的方法为下层地址--》/hello/chen）</span></span><br><span class="line"><span class="comment">//@RequestMapping(&quot;/hello&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//映射访问路径</span></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/chen&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">hello</span><span class="params">(Model model,HttpSession session)</span>&#123;</span><br><span class="line">          <span class="comment">//封装数据</span></span><br><span class="line">          model.addAttribute(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;Hello,SpringMVCAnnotation&quot;</span>);</span><br><span class="line">          <span class="keyword">return</span> <span class="string">&quot;hello&quot;</span>;   <span class="comment">//会被视图解析器处理</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<h2 id="4、前端视图"><a href="#4、前端视图" class="headerlink" title="4、前端视图"></a>4、前端视图</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230608152525242.png" alt="image-20230608152525242"></p>
<br/>



<blockquote>
<p>使用spring MVC必须配置的三大件：</p>
<ul>
<li><strong>处理器映射器、处理器适配器、视图解析器</strong></li>
<li>通常，我们只需要<strong>手动配置视图解析器</strong>，而<strong>处理器映射器</strong>和<strong>处理器适配器</strong>只需要开启注解驱动即可，而省去了大段的xm配置</li>
</ul>
</blockquote>
<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="Controller-1"><a href="#Controller-1" class="headerlink" title="Controller"></a>Controller</h1><p><strong>控制器Controller</strong></p>
<ul>
<li>控制器复杂提供访问应用程序的行为，通常通过接口定义或<strong>注解</strong>定义两种方法实现。</li>
<li>控制器负责解析用户的请求并将其转换为一个模型。</li>
<li>在Spring MVC中一个控制器类可以包含多个方法</li>
<li>在Spring MVC中，对于Controller的配置方式有很多种</li>
</ul>
<br/>



<h2 id="1、实现Controller接口【非注解】"><a href="#1、实现Controller接口【非注解】" class="headerlink" title="1、实现Controller接口【非注解】"></a>1、实现Controller接口【非注解】</h2><ul>
<li><blockquote>
<p>参考上面 <strong>HelloSpringMVC</strong></p>
</blockquote>
</li>
</ul>
<br/>

<br/>



<h2 id="2、-Controller【注解】"><a href="#2、-Controller【注解】" class="headerlink" title="2、@Controller【注解】"></a>2、@Controller【注解】</h2><ul>
<li><h3 id="Controller-2"><a href="#Controller-2" class="headerlink" title="@Controller"></a>@Controller</h3><ul>
<li><p>@Control1er注解的类会自动添加到spring上下文中</p>
</li>
<li><p>被这个注解的类所有的方法，如果返回值是<strong>String</strong>,并且有具体页面可以跳转，那么就会被视图解析器解析：</p>
</li>
</ul>
</li>
</ul>
<br/>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span> <span class="comment">//代表这个类spring托管</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ControllerTest2</span> &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h2 id="3、-RequestMapping"><a href="#3、-RequestMapping" class="headerlink" title="3、@RequestMapping"></a>3、@RequestMapping</h2><ul>
<li><p>当只有一个参数，value可以省略  <strong>@RequestMapping(value&#x3D;”value&#x2F;t2”)</strong></p>
</li>
<li><p>映射访问路径  – （置于类上+方法上 &#x3D;&#x3D;父子组件路径)  – 方法上–单路径</p>
</li>
<li><blockquote>
<p>项目中遇到的映射请求配置：</p>
<p><strong>@RequestMapping(value &#x3D; “路径”, method &#x3D; RequestMethod.POST )</strong></p>
</blockquote>
<br/></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ControllerTest3</span> &#123;</span><br><span class="line">	</span><br><span class="line">    <span class="comment">//映射访问路径</span></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/t2&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">test2</span><span class="params">(Model model)</span>&#123;</span><br><span class="line">        <span class="comment">//Spring MVC会自动实例化一个Model对象用于向视图中传值</span></span><br><span class="line">        model.addAttribute(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;ControllerTest2&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//返回请求地址</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;test2&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/t3&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">test3</span><span class="params">(Model model)</span>&#123;</span><br><span class="line">        model.addAttribute(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;test3&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;test3&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>访问路径：http :&#x2F;&#x2F;localhost:8084&#x2F;t2</p>
</blockquote>
<ul>
<li>同时注解类与方法</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/c3&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ControllerTest3</span> &#123;</span><br><span class="line">	</span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/t2&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">test3</span><span class="params">(Model model)</span>&#123;</span><br><span class="line">        model.addAttribute(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;ControllerTest3&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br><span class="line">         <span class="comment">//return &quot;admin/test&quot;;</span></span><br><span class="line">    &#125;</span><br><span class="line">     </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p>访问路径：http: &#x2F;&#x2F;localhost:8084&#x2F;c3&#x2F;t2</p>
</blockquote>
<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="Restful风格"><a href="#Restful风格" class="headerlink" title="Restful风格"></a>Restful风格</h1><ul>
<li><p>安全，隐藏参数</p>
</li>
<li><p>&#x2F; 为url分隔符，（参数、页面）</p>
</li>
</ul>
<br/>

<h2 id="PathVariable-1"><a href="#PathVariable-1" class="headerlink" title="@PathVariable"></a>@PathVariable</h2><ul>
<li>在Spring MVC中可以使用@PathVariable注解，让方法参数的值对应绑定到一个URI模板变量</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">RestFulController</span> &#123;</span><br><span class="line">     </span><br><span class="line">    <span class="comment">//@RequestMapping(value=&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;,method = RequestMethod.GET)</span></span><br><span class="line">     <span class="meta">@RequestMapping(&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">test1</span><span class="params">(<span class="meta">@PathVariable(&quot;a&quot;)</span> <span class="type">int</span> a,<span class="meta">@PathVariable(&quot;b&quot;)</span> <span class="type">int</span> b, Model model)</span>&#123;</span><br><span class="line">        <span class="type">int</span> res=a+b;</span><br><span class="line">        model.addAttribute(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;结果集为：&quot;</span>+res);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">     </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>原来的   ：http :&#x2F;&#x2F;localhost:8084&#x2F;add?a&#x3D;1&amp;b&#x3D;1</p>
<p>RestFul : http :&#x2F;&#x2F;localhost:8084&#x2F;add&#x2F;a&#x2F;b</p>
</blockquote>
<br/>

<ul>
<li>简化注解实现@RequestMapping中的method</li>
<li>@RequestMapping(name&#x3D;”&#x2F;add&#x2F;{a}&#x2F;{b}”,method &#x3D; RequestMethod.GET)</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//根据请求方法实现路径映射注解  == RequestMapping(name=&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;,method = RequestMethod.方法)</span></span><br><span class="line"><span class="meta">@GetMapping</span>	-----  <span class="meta">@GetMapping(&quot;/add/&#123;a&#125;/&#123;b&#125;&quot;)</span></span><br><span class="line"><span class="meta">@PostMapping</span></span><br><span class="line"><span class="meta">@PutMapping</span></span><br><span class="line"><span class="meta">@DeleteMapping</span></span><br><span class="line"><span class="meta">@PatchMapping</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="结果跳转方式"><a href="#结果跳转方式" class="headerlink" title="结果跳转方式"></a>结果跳转方式</h1><p>设置ModelAndView对象，根据vilew的名称，和视图解析器跳转到指定的页面</p>
<p>页面：「视图解析器前缀] + viewName +「视图解析器后缀]</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--视图解析器--&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;</span></span></span><br><span class="line"><span class="tag">        <span class="attr">id</span>=<span class="string">&quot;internalResourceviewResolver&quot;</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--前缀--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;prefix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;/WEB-INF/jsp/&quot;</span>/&gt;</span></span><br><span class="line">      <span class="comment">&lt;!--后缀--&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;suffix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;.jsp&quot;</span>/&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<p>对应的controller类【不使用注解】</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ControllerTest1</span> <span class="keyword">implements</span> <span class="title class_">Controller</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> ModelAndView <span class="title function_">handleRequest</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//处理请求且返回一个模型与视图对象</span></span><br><span class="line">        ModelAndView mv=<span class="keyword">new</span> <span class="title class_">ModelAndView</span>();</span><br><span class="line">        mv.addObject(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;ControllerTest1&quot;</span>);</span><br><span class="line">        mv.setViewName(<span class="string">&quot;test&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> mv;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<p>【使用注解】</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ControllerTest2</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//映射访问路径</span></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/t2&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">test2</span><span class="params">(Model model)</span>&#123;</span><br><span class="line">        model.addAttribute(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;ControllerTest2&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//返回请求地址</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<ul>
<li><h2 id="原生ServletAPI"><a href="#原生ServletAPI" class="headerlink" title="原生ServletAPI"></a>原生ServletAPI</h2></li>
</ul>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230608174757674.png" alt="image-20230608174757674"></p>
<br/>

<hr>
<p>1、<strong>配置视图解析器</strong></p>
<ul>
<li><p>不需要全命名</p>
</li>
<li><p><strong>默认是转发</strong>（拼接下一页url），不改变url</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//转发</span></span><br><span class="line"><span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br></pre></td></tr></table></figure>

<br/>

<ul>
<li>重定向（跳转去指定页面）<ul>
<li><strong>redirect:&#x2F;</strong></li>
</ul>
</li>
</ul>
<p>重定向，不需要视图解析器，本质就重新请求一个新地方，所以注意路径问题</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//重定向</span></span><br><span class="line"><span class="keyword">return</span> <span class="string">&quot;redirect:/index.jsp&quot;</span>;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<p>2、<strong>不配置视图解析器</strong></p>
<ul>
<li>全命名–加前缀和后缀</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//转发一  --前缀加 /</span></span><br><span class="line"><span class="keyword">return</span> <span class="string">&quot;/WEB-INF/jsp/test.jsp&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//转发二</span></span><br><span class="line"><span class="keyword">return</span> <span class="string">&quot;forward:/WEB-INF/jsp/test.jsp&quot;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//重定向</span></span><br><span class="line"><span class="keyword">return</span>  <span class="string">&quot;redirect:/WEB-INF/jsp/test.jsp&quot;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<hr>
<br/>

<br/>



<h1 id="数据处理"><a href="#数据处理" class="headerlink" title="数据处理"></a>数据处理</h1><h2 id="接收数据"><a href="#接收数据" class="headerlink" title="接收数据"></a>接收数据</h2><p>1、<strong>提交的域名称和处理方法的参数名一致</strong></p>
<p>提交数据：http:&#x2F;localhost:8080&#x2F;hello?name&#x3D;chen</p>
<p>处理方法：</p>
<ul>
<li><strong>@RequestParam(“url中参数名”)</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/hello&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">test1</span><span class="params">(<span class="meta">@RequestParam(&quot;name&quot;)</span> String name,HttpSession session)</span>&#123;</span><br><span class="line">    <span class="comment">//接收前端参数</span></span><br><span class="line">    System.out.println(<span class="string">&quot;接收到前端的参数为：&quot;</span>+name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<p>2、<strong>提交的域名称和处理方法的参数名不一致</strong></p>
<p>提交数据：http:&#x2F;localhost:8080&#x2F;hello?username&#x3D;chen</p>
<p>处理方法：</p>
<ul>
<li><strong>@RequestParam(“url中参数名”)</strong>  <strong>映射字段</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/hello&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">test1</span><span class="params">(<span class="meta">@RequestParam(&quot; username&quot;)</span> String name)</span>&#123;</span><br><span class="line">    <span class="comment">//接收前端参数</span></span><br><span class="line">    System.out.println(<span class="string">&quot;接收到前端的参数为：&quot;</span>+name);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<p>3、**@RequestBody** 从请求体中，获取数据，转为形参的对象</p>
<p> 从请求体中，获取数据，转为形参的对象</p>
<p>1、前端是json格式的数据,例如{id:1001,name:”Lisi”}</p>
<p>2、后端控制器方法，使用java对象接收参数，加入@RequestBody</p>
<p>3、服务器接收json转为对象，需要在对象类型的形参前面加入@RequestBody</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@PostMapping(&quot;/user/json&quot;)</span></span><br><span class="line"><span class="keyword">public</span> User <span class="title function_">addUserJsonUser</span><span class="params">(<span class="meta">@RequestBody</span> User user)</span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<br/>

<p><strong>3、接收的参数为对象类型</strong></p>
<p>1.接收前端用户传递的参数，判断参数的名字，假设名字直接在方法上，可以直接使用</p>
<p>2.假设传递的是一个对User,匹配User对象中的字段名：如果名字一致则OK,否则，匹配不到Null</p>
<ul>
<li>实体类</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@AllArgsConstructor</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">User</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="type">int</span> id;</span><br><span class="line">    <span class="keyword">private</span>  String name;</span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> age;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<ul>
<li><p>提交数据：localhost:8084&#x2F;t2?id&#x3D;1&amp;name&#x3D;陈呀&amp;age&#x3D;18</p>
</li>
<li><p>处理方法：要求提交的表单和对象的属性一致，参数使用对象即可</p>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/user&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">test2</span><span class="params">(User user)</span>&#123;</span><br><span class="line">    System.out.println(user);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p><strong>说明：如果使用对象的话，前端传递的参数名和对象名必须一致，否则就是null。</strong></p>
</blockquote>
<br/>

<br/>



<h2 id="数据显示到前端"><a href="#数据显示到前端" class="headerlink" title="数据显示到前端"></a>数据显示到前端</h2><p><strong>第一种：通过ModelAndView</strong>【非注解】</p>
<ul>
<li>addObject</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ControllerTest1</span> <span class="keyword">implements</span> <span class="title class_">Controller</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> ModelAndView <span class="title function_">handleRequest</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">         </span><br><span class="line">        <span class="comment">//处理请求且返回一个模型与视图对象</span></span><br><span class="line">        ModelAndView mv=<span class="keyword">new</span> <span class="title class_">ModelAndView</span>();</span><br><span class="line">        mv.addObject(<span class="string">&quot;msg&quot;</span>,<span class="string">&quot;ControllerTest1&quot;</span>);</span><br><span class="line">        mv.setViewName(<span class="string">&quot;test&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> mv;</span><br><span class="line">         </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>



<p><strong>第二种：通过ModelMap</strong></p>
<p>ModelMap</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/t1&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">test1</span><span class="params">(<span class="meta">@RequestParam(&quot;username&quot;)</span> String name, ModelMap model)</span>&#123;</span><br><span class="line">    <span class="comment">//将返回的结果传输给前端,model</span></span><br><span class="line">    model.addAttribute(<span class="string">&quot;msg&quot;</span>,name);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>



<p><strong>第三种：通过Model【重点】</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@GetMapping(&quot;/t1&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">test1</span><span class="params">(<span class="meta">@RequestParam(&quot;username&quot;)</span> String name, Model model)</span>&#123;</span><br><span class="line">    <span class="comment">//1.接收前端参数</span></span><br><span class="line">    System.out.println(<span class="string">&quot;接收到前端的参数为：&quot;</span>+name);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//2.将返回的结果传输给前端,model</span></span><br><span class="line">    model.addAttribute(<span class="string">&quot;msg&quot;</span>,name);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//3.视图跳转</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;test&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<blockquote>
<h2 id="对比"><a href="#对比" class="headerlink" title="对比"></a>对比</h2><p>Model	只有寥寥几个方法只适合用丁储存数据，简化了新于对丁Model对象的操作和理解</p>
<p>ModelMap	继承了LinkedMap:除了实现了自身的一些方法，同样的继承LinkedMap的方法和特性</p>
<p>ModelAndview	可以在储存数据的同时，可以进行设置返回的逻辑视图，进行控制展示层的跳转。</p>
</blockquote>
<br/>

<br/>

<hr>
<br/>

<br/>



<h1 id="乱码问题"><a href="#乱码问题" class="headerlink" title="乱码问题"></a>乱码问题</h1><p>1、自定义过滤器</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.chen.filter;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.*;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"><span class="keyword">import</span> java.util.logging.LogRecord;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">EncodingFilter</span>  <span class="keyword">implements</span> <span class="title class_">Filter</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">(FilterConfig filterConfig)</span> <span class="keyword">throws</span> ServletException &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">doFilter</span><span class="params">(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)</span> <span class="keyword">throws</span> IOException, ServletException &#123;</span><br><span class="line">        servletRequest.setCharacterEncoding(<span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line">        servletResponse.setCharacterEncoding(<span class="string">&quot;utf-8&quot;</span>);</span><br><span class="line">        filterChain.doFilter(servletRequest,servletResponse);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">destroy</span><span class="params">()</span> &#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>在web.xml中注册</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>com.chen.filter.EncodingFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<p><strong>2、Spring提供在web.xml中配置</strong>【重点】</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--2.配置SpringMVC乱码过滤--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>org.springframework.web.filter.CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>utf-8<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>



<blockquote>
<p>1、修改tomcat配置文件：设置编码</p>
<p>包–conf–servel.xml</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">Connector</span> <span class="attr">URIEncoding</span>=<span class="string">&quot;utf-8&quot;</span><span class="attr">port</span>=<span class="string">&quot;8080&quot;</span><span class="attr">protocol</span>=<span class="string">&quot;HTTP/1.1&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">connectionTimeout</span>=<span class="string">&quot;20000&quot;</span></span></span><br><span class="line"><span class="tag">       <span class="attr">redirectport</span>=<span class="string">&quot;8443&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>


</blockquote>
<br/>

<br/>

<hr>
<br/>

<br/>



<h1 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h1><ul>
<li><p>对象表示为键值对，数据由逗号分隔</p>
</li>
<li><p>花括号保存对象</p>
</li>
<li><p>方括号保存数组</p>
<br/>

<br/></li>
</ul>
<p>前端</p>
<p>对象转json  –  JSON.stringify(  );</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//编写一个JavaScript 对象</span></span><br><span class="line"><span class="keyword">let</span> user=&#123;</span><br><span class="line">    name : <span class="string">&quot;辰呀&quot;</span>,</span><br><span class="line">    <span class="attr">age</span>:<span class="number">3</span>,</span><br><span class="line">    <span class="attr">sex</span>:<span class="string">&quot;男&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//js对象转json对象</span></span><br><span class="line"><span class="keyword">let</span> json = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(user);</span><br></pre></td></tr></table></figure>

<br/>

<p>JSON对象 转 js 对象  –  JSON.parse(   )</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//将JSON 对象转换为JavaScript对象</span></span><br><span class="line"><span class="keyword">let</span> obj =<span class="title class_">JSON</span>.<span class="title function_">parse</span>(json)</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;obj&quot;</span>,obj)</span><br></pre></td></tr></table></figure>

<br/>

<br/>



<h2 id="Jackson"><a href="#Jackson" class="headerlink" title="Jackson"></a>Jackson</h2><h3 id="1、导入依赖"><a href="#1、导入依赖" class="headerlink" title="1、导入依赖"></a>1、导入依赖</h3><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Jackson --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jackson-databind<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.15.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<h3 id="2、乱码解决"><a href="#2、乱码解决" class="headerlink" title="2、乱码解决"></a>2、乱码解决</h3><ul>
<li>springmvc-servlet.xml配置文件</li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--JS0N乱码问题配置--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mvc:annotation-driven</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">mvc:message-converters</span> <span class="attr">register-defaults</span>=<span class="string">&quot;true&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.http.converter.StringHttpMessageConverter&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">constructor-arg</span> <span class="attr">value</span>=<span class="string">&quot;UTF-8&quot;</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;objectMapper&quot;</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean&quot;</span>&gt;</span></span><br><span class="line">                    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;failOnEmptyBeans&quot;</span> <span class="attr">value</span>=<span class="string">&quot;false&quot;</span>/&gt;</span></span><br><span class="line">                <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">mvc:message-converters</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">mvc:annotation-driven</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<blockquote>
<p>原生方案：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value = &quot;j1&quot;, produces = &quot;application/json;charset=utf-8&quot;)</span></span><br></pre></td></tr></table></figure>


</blockquote>
<br/>

<h3 id="3、测试"><a href="#3、测试" class="headerlink" title="3、测试"></a>3、测试</h3><p><strong>前后端分离，不需要跳转视图，只返回数据，不要@Controller</strong></p>
<p><strong>@RestController 【放在类上】</strong></p>
<p> **@ResponseBody 【放在方法上】  **</p>
<ul>
<li>写入json数据：writeValueAsString</li>
</ul>
<br/>

<ul>
<li><h2 id="对象–转为Json"><a href="#对象–转为Json" class="headerlink" title="对象–转为Json"></a>对象–转为Json</h2></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//@Controller</span></span><br><span class="line"><span class="meta">@ResponseBody</span> <span class="comment">//整个类不会走视图解析器，不跳转界面，直接返回一个字符串</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UserController</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;j1&quot;)</span></span><br><span class="line">    <span class="meta">@ResponseBody</span><span class="comment">//当前方法不会走视图解析器，不跳转界面，直接返回一个字符串</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">json1</span><span class="params">()</span> <span class="keyword">throws</span> JsonProcessingException &#123;</span><br><span class="line">         </span><br><span class="line">        <span class="type">User</span> <span class="variable">user</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰1&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">         </span><br><span class="line">        <span class="comment">//jackson,ObjectMapper</span></span><br><span class="line">        ObjectMapper mapper=<span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line">        <span class="type">String</span> <span class="variable">str</span> <span class="operator">=</span> mapper.writeValueAsString(user);</span><br><span class="line">         </span><br><span class="line">        <span class="keyword">return</span> str.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>



<blockquote>
<h2 id="代码复用–抽取为工具类"><a href="#代码复用–抽取为工具类" class="headerlink" title="代码复用–抽取为工具类"></a>代码复用–抽取为工具类</h2><ul>
<li>创建工具类JsonUtils</li>
<li>最终只是写入json</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">JsonUtils</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getJson</span><span class="params">(Object object)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> getJson(object,<span class="string">&quot;yyyy-MM--dd HH:mm:ss&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//将传递的 时间戳 转为 单位时间</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String <span class="title function_">getJson</span><span class="params">(Object object,String dateFormt)</span>&#123;</span><br><span class="line">        ObjectMapper mapper=<span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//不使用时间戳的方式</span></span><br><span class="line">        <span class="comment">//1.使用ObjectMapper(false=不使用时间戳的方式输出，即显示单位)</span></span><br><span class="line">       mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,<span class="literal">false</span>);</span><br><span class="line">        <span class="comment">//自定义日期的格式</span></span><br><span class="line">        <span class="type">SimpleDateFormat</span> <span class="variable">sdf</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">SimpleDateFormat</span>(dateFormt);</span><br><span class="line">        mapper.setDateFormat(sdf);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> mapper.writeValueAsString(object);</span><br><span class="line">        &#125;<span class="keyword">catch</span> (JsonProcessingException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span>  <span class="literal">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


</blockquote>
<br/>

<br/>



<ul>
<li><h2 id="列表–转为Json"><a href="#列表–转为Json" class="headerlink" title="列表–转为Json"></a>列表–转为Json</h2></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value = &quot;j2&quot;)</span></span><br><span class="line"><span class="meta">@ResponseBody</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">json2</span><span class="params">()</span> <span class="keyword">throws</span> JsonProcessingException &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//jackson,ObjectMapper</span></span><br><span class="line">    ObjectMapper mapper=<span class="keyword">new</span> <span class="title class_">ObjectMapper</span>();</span><br><span class="line"></span><br><span class="line">    List&lt;User&gt; userList=<span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;User&gt;();</span><br><span class="line">    <span class="comment">//创建一个对象</span></span><br><span class="line">    <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰1&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">    <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰2&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">    <span class="type">User</span> <span class="variable">user3</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰3&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">    <span class="type">User</span> <span class="variable">user4</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰4&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">    <span class="type">User</span> <span class="variable">user5</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰5&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line"></span><br><span class="line">    userList.add(user1);</span><br><span class="line">    userList.add(user2);</span><br><span class="line">    userList.add(user3);</span><br><span class="line">    userList.add(user4);</span><br><span class="line">    userList.add(user5);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> JsonUtils.getJson(userList);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>

<br/>



<ul>
<li><h2 id="时间Date–转为Json"><a href="#时间Date–转为Json" class="headerlink" title="时间Date–转为Json"></a>时间Date–转为Json</h2></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value = &quot;j3&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">json3</span><span class="params">()</span> <span class="keyword">throws</span> JsonProcessingException &#123;</span><br><span class="line"></span><br><span class="line">    <span class="type">Date</span> <span class="variable">date</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Date</span>();</span><br><span class="line">    <span class="keyword">return</span> JsonUtils.getJson(date,<span class="string">&quot;yyyy-MM--dd HH:mm:ss&quot;</span>);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<br/>

<br/>





<h2 id="FastJson"><a href="#FastJson" class="headerlink" title="FastJson"></a>FastJson</h2><p>json对象 &lt;&#x3D;&#x3D;&gt; JavaBean &lt; &#x3D;&#x3D; &gt;  json字符串</p>
<p> 依赖 </p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.alibaba<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>fastjson<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.2.60<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<p><strong>fastjson三个主要的类</strong>：</p>
<ul>
<li><p>【JSONObject代表json对象】</p>
<ul>
<li>JSONObject实现了Map接口，猜想JSONObject底层操作是由Map实现的。</li>
<li>JSONObjecti对应json对象，通过各种形式的get0方法可以获取json对象中的数据，也可利用诸如size(),isEmpty()等方法获取”键：值”对的个数和判断是否为空。其本质是通过实现Map接口并调用接口中的方法完成的。</li>
</ul>
<br/>
</li>
<li><p>【JSONArray代表json对象数组】</p>
<ul>
<li>内部是有Lst接口中的方法来完成操作的。</li>
</ul>
<br/>
</li>
<li><p>【JSON代表JSONObject和)SONArray的转化】</p>
<ul>
<li><p>JSON类源码分析与使用</p>
</li>
<li><p>仔细观察这些方法，主要是实现json对象，json对象数组，javabean对象，json字符串之间的相互转化。</p>
</li>
</ul>
</li>
</ul>
<br/>

<ul>
<li>直接导入类即可  <strong>JSON.方法</strong>【无需new ObjectMapper();】</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">  <span class="meta">@RequestMapping(value = &quot;j2&quot;)</span></span><br><span class="line">  <span class="meta">@ResponseBody</span></span><br><span class="line">  <span class="keyword">public</span> String <span class="title function_">json2</span><span class="params">()</span> <span class="keyword">throws</span> JsonProcessingException &#123;</span><br><span class="line"></span><br><span class="line">      List&lt;User&gt; userList=<span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;User&gt;();</span><br><span class="line">      <span class="comment">//创建一个对象</span></span><br><span class="line">      <span class="type">User</span> <span class="variable">user1</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰1&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">      <span class="type">User</span> <span class="variable">user2</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰2&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">      <span class="type">User</span> <span class="variable">user3</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰3&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">      <span class="type">User</span> <span class="variable">user4</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰4&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line">      <span class="type">User</span> <span class="variable">user5</span> <span class="operator">=</span><span class="keyword">new</span> <span class="title class_">User</span>(<span class="string">&quot;辰5&quot;</span>,<span class="number">3</span>,<span class="string">&quot;男&quot;</span>);</span><br><span class="line"></span><br><span class="line">      userList.add(user1);</span><br><span class="line">      userList.add(user2);</span><br><span class="line">      userList.add(user3);</span><br><span class="line">      userList.add(user4);</span><br><span class="line">      userList.add(user5);</span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">&quot;****java对象转JS0N字符串****&quot;</span>);</span><br><span class="line">      <span class="type">String</span> <span class="variable">str1</span> <span class="operator">=</span> JSON.toJSONString(userList);</span><br><span class="line">      System.out.println(<span class="string">&quot;JSON.toJSONString(userList)==&gt;&quot;</span>+str1);</span><br><span class="line">      <span class="type">String</span> <span class="variable">str2</span> <span class="operator">=</span>  JSON.toJSONString(user1);</span><br><span class="line">      System.out.println(<span class="string">&quot;JSON.toJSONString(user1)==&gt;&quot;</span>+str2);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">&quot;\n****JS0N字符串 转 JaVa对象***&quot;</span>);</span><br><span class="line">      User jp_user1=JSON.parseObject(str2,User.class);</span><br><span class="line">      System.out.println(<span class="string">&quot;JSON.parseobject(str2,User.class)==&gt;&quot;</span>+jp_user1);</span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">&quot;\n****JaVa对象 转 JS0N对象***&quot;</span>);</span><br><span class="line">      <span class="type">JSONObject</span> <span class="variable">jsonobject1</span> <span class="operator">=</span> (JSONObject)JSON.toJSON(user2);</span><br><span class="line">      System.out.println(<span class="string">&quot;(JSONObject)JSON.toJSON(user2)==&gt;&quot;</span>+jsonobject1.getString(<span class="string">&quot;name&quot;</span>));</span><br><span class="line"></span><br><span class="line">      System.out.println(<span class="string">&quot;\n***JS0N对象 转 JaVa对象****&quot;</span>);</span><br><span class="line">      <span class="type">User</span> <span class="variable">to_java_user</span> <span class="operator">=</span> JSON.toJavaObject(jsonobject1,User.class);</span><br><span class="line">      System.out.println(<span class="string">&quot;JSON.toJavaobject(jsonobject1,User.class)==&gt;&quot;</span>+to_java_user);</span><br><span class="line">       </span><br><span class="line">       <span class="comment">//获取json中指定数据--转为map</span></span><br><span class="line">        String json:=<span class="string">&quot;&#123;&quot;</span>age\<span class="string">&quot;:30,\&quot;id\&quot;:5671,\&quot;name\&quot;:\&quot;周畅&quot;</span>&#125;<span class="string">&quot;；</span></span><br><span class="line"><span class="string">        JSONObject jsonobject = JSONObject.parseobject(json);</span></span><br><span class="line"><span class="string">        //JSONObject是-个map</span></span><br><span class="line"><span class="string">        String name jsonobject.getstring(key:&quot;</span>name<span class="string">&quot;);</span></span><br><span class="line"><span class="string">        System.out.println (&quot;</span>name=<span class="string">&quot;+name);</span></span><br><span class="line"><span class="string">        int age jsonobject.getIntValue(key:&quot;</span>age<span class="string">&quot;);</span></span><br><span class="line"><span class="string">        System.out.println(&quot;</span>age =<span class="string">&quot;age);</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">//对象中存在对象</span></span><br><span class="line"><span class="string">        Stringstring JSONObject.parseobject(json).getJSONObject(&quot;</span>school<span class="string">&quot;).getstring(key:&quot;</span>address<span class="string">&quot;);	</span></span><br><span class="line"><span class="string">       </span></span><br><span class="line"><span class="string">       </span></span><br><span class="line"><span class="string">      return &quot;</span>hello<span class="string">&quot;;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br></pre></td></tr></table></figure>



<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="HttpClient"><a href="#HttpClient" class="headerlink" title="HttpClient"></a>HttpClient</h1><ul>
<li>调用第三方接口</li>
</ul>
<p>一个开源的 HTTP 客户端库，它允许您以<strong>编程方式发送 HTTP 请求并处理 HTTP 响应</strong>。它提供了简单、灵活的 API，可用于与 Web 服务器进行通信。</p>
<br/>

<h2 id="依赖-1"><a href="#依赖-1" class="headerlink" title="依赖"></a>依赖</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.httpcomponents<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>httpclient<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.5.13<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<h2 id="Get方式"><a href="#Get方式" class="headerlink" title="Get方式"></a>Get方式</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testGet</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="comment">//发起get请求，编程方式处理http请求。</span></span><br><span class="line">    String url=<span class="string">&quot;https://restapi.amap.com/v3/ip?key=0113a13c88697dcea6a445584d535837&amp;ip=60.25.188.64&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//1、创建HttpClient对象</span></span><br><span class="line">    <span class="type">CloseableHttpClient</span> <span class="variable">client</span> <span class="operator">=</span> HttpClients.createDefault();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//2.创建HttpGet对象</span></span><br><span class="line">    <span class="type">HttpGet</span> <span class="variable">httpGet</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">HttpGet</span>(url);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//3.执行请求，使用client对象的方法，执行请求后获取返回结果</span></span><br><span class="line">    <span class="comment">//CloseableHttpResponse是返回结果，相当于HttpServletResponse</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="type">CloseableHttpResponse</span> <span class="variable">response</span> <span class="operator">=</span> client.execute(httpGet);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//从response获取应答消息</span></span><br><span class="line">        <span class="keyword">if</span> (response.getStatusLine().getStatusCode()== HttpStatus.SC_OK)&#123;</span><br><span class="line">            <span class="comment">//4、获取数据</span></span><br><span class="line">            <span class="comment">//response.getEntity().getContent();//数据</span></span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> EntityUtils.toString(response.getEntity());</span><br><span class="line">            System.out.println(<span class="string">&quot;访问ip的应答结果：&quot;</span> + json);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;<span class="keyword">catch</span> (Exception e)&#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">//5、关闭资源</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            client.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<h2 id="Post方式"><a href="#Post方式" class="headerlink" title="Post方式"></a>Post方式</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">testPsot</span><span class="params">()</span>&#123;</span><br><span class="line">    <span class="comment">//1、创建HttpClient对象</span></span><br><span class="line">    <span class="type">CloseableHttpClient</span> <span class="variable">client</span> <span class="operator">=</span> HttpClients.createDefault();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//2、创建HttpPost对象，表示post请求</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">url</span> <span class="operator">=</span> <span class="string">&quot;https://restapi.amap.com/v3/ip&quot;</span>;</span><br><span class="line">    <span class="type">HttpPost</span> <span class="variable">httpPost</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">HttpPost</span>(url);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//3、准备post请求的参数</span></span><br><span class="line">    List&lt;NameValuePair&gt; params =<span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;NameValuePair&gt;();</span><br><span class="line">    <span class="comment">//添加参数 BasicNameValuePair类，实现了NameValuePair接口</span></span><br><span class="line">    <span class="comment">//                          BasicNameValuePair(参数名，参数值)</span></span><br><span class="line">    params.add(<span class="keyword">new</span> <span class="title class_">BasicNameValuePair</span>(<span class="string">&quot;key&quot;</span>,<span class="string">&quot;0113a13c88697dcea6a445584d535837&quot;</span>));</span><br><span class="line">    params.add(<span class="keyword">new</span> <span class="title class_">BasicNameValuePair</span>(<span class="string">&quot;ip&quot;</span>,<span class="string">&quot;60.25.188.64&quot;</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">//4、设置HttpPost使用参数</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        httpPost.setEntity(<span class="keyword">new</span> <span class="title class_">UrlEncodedFormEntity</span>(params));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5、执行请求</span></span><br><span class="line">        <span class="type">CloseableHttpResponse</span> <span class="variable">response</span> <span class="operator">=</span> client.execute(httpPost);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//6、读取数据</span></span><br><span class="line">        <span class="keyword">if</span> (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)&#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">json</span> <span class="operator">=</span> EntityUtils.toString(response.getEntity());</span><br><span class="line">            System.out.println(<span class="string">&quot;json=&quot;</span> + json);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h1><ul>
<li>Spring MVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。</li>
</ul>
<p><strong>过滤器与拦截器的区别</strong>：拦截器是AOP思想的具体应用,把当前拦截器横切入当前访问的控制器</p>
<ul>
<li>拦截器只会<strong>拦截访问的控制器</strong>方法，如果访问的是jsp&#x2F;html&#x2F;css&#x2F;image&#x2F;js.是不会进行拦截的-</li>
</ul>
<br/>

<h2 id="1、自定义拦截类"><a href="#1、自定义拦截类" class="headerlink" title="1、自定义拦截类"></a>1、自定义拦截类</h2><p>实现 <strong>HandlerInterceptor</strong> 接口，重写全部方法</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyInterceptor</span> <span class="keyword">implements</span> <span class="title class_">HandlerInterceptor</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//return ture;  	执行下一个拦截器，放行</span></span><br><span class="line">    <span class="comment">//return false; 	不执行下一个拦截器</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">preHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;==================方法处理前==================&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">postHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;==================方法处理后==================&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">afterCompletion</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;==================清理==================&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h2 id="2、配置拦截器"><a href="#2、配置拦截器" class="headerlink" title="2、配置拦截器"></a>2、配置拦截器</h2><ul>
<li><h2 id="spring-mvc-xml"><a href="#spring-mvc-xml" class="headerlink" title="spring-mvc.xml"></a>spring-mvc.xml</h2></li>
</ul>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--视图解析器--&gt;</span></span><br><span class="line"></span><br><span class="line"> <span class="comment">&lt;!--拦截器配置--&gt;</span></span><br><span class="line"> <span class="tag">&lt;<span class="name">mvc:interceptors</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">mvc:interceptor</span>&gt;</span></span><br><span class="line">         <span class="comment">&lt;!--包括这个请求下面的所有的请求--&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">mvc:mapping</span> <span class="attr">path</span>=<span class="string">&quot;/**/&quot;</span>/&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;com.chen.config.MyInterceptor&quot;</span>/&gt;</span></span><br><span class="line">     <span class="tag">&lt;/<span class="name">mvc:interceptor</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">mvc:interceptors</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<blockquote>
<ul>
<li>输出结果（<strong>AOP</strong>）</li>
</ul>
<p>————–方法处理前————–</p>
<p>Intercepter &#x3D;&#x3D;&gt; test()方法执行了</p>
<p> ————–方法处理后————–</p>
<p>——————清理——————-</p>
</blockquote>
<br/>

<br/>

<h2 id="3、常用【登录判断拦截】"><a href="#3、常用【登录判断拦截】" class="headerlink" title="3、常用【登录判断拦截】"></a>3、常用【登录判断拦截】</h2><ul>
<li><strong>拦截类</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyInterceptor</span> <span class="keyword">implements</span> <span class="title class_">HandlerInterceptor</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//return ture;  执行下一个拦截器，放行</span></span><br><span class="line">    <span class="comment">//return false; 不执行下一个拦截器</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="type">boolean</span> <span class="title function_">preHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;==================方法处理前==================&quot;</span>);</span><br><span class="line">        <span class="type">HttpSession</span> <span class="variable">session</span> <span class="operator">=</span> request.getSession();</span><br><span class="line">        <span class="comment">//放行：判断什么情况下登录</span></span><br><span class="line">        <span class="comment">//登录页面也会放行</span></span><br><span class="line">        <span class="keyword">if</span> (request.getRequestURI().contains(<span class="string">&quot;登录请求的url：goLogin&quot;</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//提交登录请求</span></span><br><span class="line">        <span class="keyword">if</span> (request.getRequestURI().contains(<span class="string">&quot;  &quot;</span>))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//第一次登录，没有session</span></span><br><span class="line">        <span class="keyword">if</span> (session.getAttribute(<span class="string">&quot; sessiom中的键 &quot;</span>)!=<span class="literal">null</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">         </span><br><span class="line">        <span class="comment">//判断什么情况下没有登录</span></span><br><span class="line">        request.getRequestDispatcher(<span class="string">&quot;重定向的页面&quot;</span>).forward(request,response);</span><br><span class="line">        <span class="keyword">return</span>  <span class="literal">false</span>;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h1><h2 id="1、依赖"><a href="#1、依赖" class="headerlink" title="1、依赖"></a>1、依赖</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--文件上传--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.3<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--servlet-api导入高版本的--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>javax.servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>4.0.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<br/>

<br/>

<h2 id="2、文件上传配置"><a href="#2、文件上传配置" class="headerlink" title="2、文件上传配置"></a>2、文件上传配置</h2><figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="comment">&lt;!--文件上传配置--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;multipartResolver&quot;</span>  <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 请求的编码格式，必须和jSP的pageEncoding属性一致，以便正确读取表单的内容，默认为ISO-8859-1 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;defaultEncoding&quot;</span> <span class="attr">value</span>=<span class="string">&quot;utf-8&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 上传文件大小上限，单位为字节（10485760=10M） --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;maxUploadSize&quot;</span> <span class="attr">value</span>=<span class="string">&quot;10485760&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;maxInMemorySize&quot;</span> <span class="attr">value</span>=<span class="string">&quot;40960&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>CommonsMultipartFile 的 常用方法：</p>
<ul>
<li><strong>String getOriginalFilename()：获取上传文件的原名</strong></li>
<li><strong>InputStream getInputStream()：获取文件流</strong></li>
<li><strong>void transferTo(File dest)：将上传文件保存到一个目录文件中</strong></li>
</ul>
</blockquote>
<br/>

<br/>

<h2 id="3、代码"><a href="#3、代码" class="headerlink" title="3、代码"></a>3、代码</h2><ul>
<li>前端<ul>
<li>enctype&#x3D;”multipart&#x2F;form-data”</li>
</ul>
</li>
</ul>
<figure class="highlight jsp"><table><tr><td class="code"><pre><span class="line">&lt;form action=<span class="string">&quot;/upload&quot;</span> enctype=<span class="string">&quot;multipart/form-data&quot;</span> method=<span class="string">&quot;post&quot;</span>&gt;</span><br><span class="line">  &lt;input type=<span class="string">&quot;file&quot;</span> name=<span class="string">&quot;file&quot;</span>/&gt;</span><br><span class="line">  &lt;input type=<span class="string">&quot;submit&quot;</span> value=<span class="string">&quot;upload&quot;</span>&gt;</span><br><span class="line">&lt;/form&gt;</span><br></pre></td></tr></table></figure>

<br/>

<p><strong>Controller</strong></p>
<ul>
<li>1、方式一</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FileController</span> &#123;</span><br><span class="line">    <span class="comment">//@RequestParam(&quot;file&quot;) 将name=file控件得到的文件封装成CommonsMultipartFile 对象</span></span><br><span class="line">    <span class="comment">//批量上传CommonsMultipartFile则为数组即可</span></span><br><span class="line">    <span class="meta">@RequestMapping(&quot;/upload&quot;)</span></span><br><span class="line">    <span class="keyword">public</span> String <span class="title function_">fileUpload</span><span class="params">(<span class="meta">@RequestParam(&quot;file&quot;)</span> CommonsMultipartFile file , HttpServletRequest request)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//获取文件名 : file.getOriginalFilename();</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">uploadFileName</span> <span class="operator">=</span> file.getOriginalFilename();</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//如果文件名为空，直接回到首页！</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="string">&quot;&quot;</span>.equals(uploadFileName))&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;redirect:/index.jsp&quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;上传文件名 : &quot;</span>+uploadFileName);</span><br><span class="line"> </span><br><span class="line">        <span class="comment">//上传路径保存设置</span></span><br><span class="line">        <span class="type">String</span> <span class="variable">path</span> <span class="operator">=</span> request.getServletContext().getRealPath(<span class="string">&quot;/upload&quot;</span>);</span><br><span class="line">        <span class="comment">//如果路径不存在，创建一个</span></span><br><span class="line">        <span class="type">File</span> <span class="variable">realPath</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(path);</span><br><span class="line">        <span class="keyword">if</span> (!realPath.exists())&#123;</span><br><span class="line">            realPath.mkdir();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;上传文件保存地址：&quot;</span>+realPath);</span><br><span class="line"> </span><br><span class="line">        <span class="type">InputStream</span> <span class="variable">is</span> <span class="operator">=</span> file.getInputStream(); <span class="comment">//文件输入流</span></span><br><span class="line">        <span class="type">OutputStream</span> <span class="variable">os</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">FileOutputStream</span>(<span class="keyword">new</span> <span class="title class_">File</span>(realPath,uploadFileName)); <span class="comment">//文件输出流</span></span><br><span class="line"> </span><br><span class="line">        <span class="comment">//读取写出</span></span><br><span class="line">        <span class="type">int</span> len=<span class="number">0</span>;</span><br><span class="line">        <span class="type">byte</span>[] buffer = <span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="keyword">while</span> ((len=is.read(buffer))!=-<span class="number">1</span>)&#123;</span><br><span class="line">            os.write(buffer,<span class="number">0</span>,len);</span><br><span class="line">            os.flush();</span><br><span class="line">        &#125;</span><br><span class="line">        os.close();</span><br><span class="line">        is.close();</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;redirect:/index.jsp&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br/>

<p>2、方式二</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 采用file.Transto 来保存上传的文件</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/upload2&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String  <span class="title function_">fileUpload2</span><span class="params">(<span class="meta">@RequestParam(&quot;file&quot;)</span> CommonsMultipartFile file, HttpServletRequest request)</span> <span class="keyword">throws</span> IOException &#123;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">//上传路径保存设置</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">path</span> <span class="operator">=</span> request.getServletContext().getRealPath(<span class="string">&quot;/upload&quot;</span>);</span><br><span class="line">    <span class="type">File</span> <span class="variable">realPath</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(path);</span><br><span class="line">    <span class="keyword">if</span> (!realPath.exists())&#123;</span><br><span class="line">        realPath.mkdir();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//上传文件地址</span></span><br><span class="line">    System.out.println(<span class="string">&quot;上传文件保存地址：&quot;</span>+realPath);</span><br><span class="line"> </span><br><span class="line">    <span class="comment">//通过CommonsMultipartFile的方法直接写文件（注意这个时候）</span></span><br><span class="line">    file.transferTo(<span class="keyword">new</span> <span class="title class_">File</span>(realPath +<span class="string">&quot;/&quot;</span>+ file.getOriginalFilename()));</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;redirect:/index.jsp&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<br/>

<br/>

<hr>
<br/>

<br/>

<h1 id="文件下载"><a href="#文件下载" class="headerlink" title="文件下载"></a>文件下载</h1><ul>
<li>Controller</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;/download&quot;)</span></span><br><span class="line"><span class="keyword">public</span> String <span class="title function_">downloads</span><span class="params">(HttpServletResponse response ,HttpServletRequest request)</span> <span class="keyword">throws</span> Exception&#123;</span><br><span class="line">    <span class="comment">//要下载的图片地址</span></span><br><span class="line">    <span class="type">String</span>  <span class="variable">path</span> <span class="operator">=</span> request.getServletContext().getRealPath(<span class="string">&quot;/图片的下载地址&quot;</span>);</span><br><span class="line">    <span class="type">String</span>  <span class="variable">fileName</span> <span class="operator">=</span> <span class="string">&quot;基础语法.jpg&quot;</span>;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">//1、设置response 响应头</span></span><br><span class="line">    response.reset(); <span class="comment">//设置页面不缓存,清空buffer</span></span><br><span class="line">    response.setCharacterEncoding(<span class="string">&quot;UTF-8&quot;</span>); <span class="comment">//字符编码</span></span><br><span class="line">    response.setContentType(<span class="string">&quot;multipart/form-data&quot;</span>); <span class="comment">//二进制传输数据</span></span><br><span class="line">    <span class="comment">//设置响应头</span></span><br><span class="line">    response.setHeader(<span class="string">&quot;Content-Disposition&quot;</span>,</span><br><span class="line">            <span class="string">&quot;attachment;fileName=&quot;</span>+URLEncoder.encode(fileName, <span class="string">&quot;UTF-8&quot;</span>));</span><br><span class="line"> </span><br><span class="line">    <span class="type">File</span> <span class="variable">file</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">File</span>(path,fileName);</span><br><span class="line">    <span class="comment">//2、 读取文件--输入流</span></span><br><span class="line">    InputStream input=<span class="keyword">new</span> <span class="title class_">FileInputStream</span>(file);</span><br><span class="line">    <span class="comment">//3、 写出文件--输出流</span></span><br><span class="line">    <span class="type">OutputStream</span> <span class="variable">out</span> <span class="operator">=</span> response.getOutputStream();</span><br><span class="line"> </span><br><span class="line">    <span class="type">byte</span>[] buff =<span class="keyword">new</span> <span class="title class_">byte</span>[<span class="number">1024</span>];</span><br><span class="line">    <span class="type">int</span> index=<span class="number">0</span>;</span><br><span class="line">    <span class="comment">//4、执行 写出操作</span></span><br><span class="line">    <span class="keyword">while</span>((index= input.read(buff))!= -<span class="number">1</span>)&#123;</span><br><span class="line">        out.write(buff, <span class="number">0</span>, index);</span><br><span class="line">        out.flush();</span><br><span class="line">    &#125;</span><br><span class="line">    out.close();</span><br><span class="line">    input.close();</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>

<ul>
<li>请求</li>
</ul>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">&quot;/download&quot;</span>&gt;</span>点击下载<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">辰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/05/02/SpringMVC/">http://example.com/2023/05/02/SpringMVC/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">C·辰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/SpringMVC/">SpringMVC</a></div><div class="post_share"><div class="social-share" data-image="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/springmvc.webp" data-sites="wechat,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/05/01/XML%E7%BA%A6%E6%9D%9F%E5%92%8CJDBC%E9%A9%B1%E5%8A%A8/" title="XML约束和驱动"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Spring.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">XML约束和驱动</div></div></a></div><div class="next-post pull-right"><a href="/2023/05/02/Spring5/" title="Spring5"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Spring5.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring5</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">辰</div><div class="author-info__description">车遥马慢</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/hchenp"><i class="fab fa-github"></i><span>Gitee-HchenP</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/hchenp" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://github.com/Pxlchen?tab=projects" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="https://console.cloud.tencent.com/cos/bucket?bucket=chen-1317386995&amp;region=ap-guangzhou&amp;isPublic=true" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="mailto:1107383160@qq.com" target="_blank" title="Email"><i class="fas fa-envelope-open-text"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">C2C-Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#SpringMVC"><span class="toc-number">1.</span> <span class="toc-text">SpringMVC</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#HelloSpringMVC"><span class="toc-number">2.</span> <span class="toc-text">HelloSpringMVC</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E7%94%9F%E6%B5%81%E7%A8%8B"><span class="toc-number">2.1.</span> <span class="toc-text">原生流程</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81web-xml"><span class="toc-number">2.1.1.</span> <span class="toc-text">1、web.xml</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81springmvc-servlet-xml"><span class="toc-number">2.1.2.</span> <span class="toc-text">2、springmvc-servlet.xml</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E7%B1%BBController"><span class="toc-number">2.1.3.</span> <span class="toc-text">3、类Controller</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AE%80%E8%A6%81%E5%88%86%E6%9E%90%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="toc-number">3.</span> <span class="toc-text">简要分析执行流程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE"><span class="toc-number">4.</span> <span class="toc-text">配置</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96"><span class="toc-number">4.1.</span> <span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B3%A8%E8%A7%A3"><span class="toc-number">4.2.</span> <span class="toc-text">注解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Controller"><span class="toc-number">4.2.1.</span> <span class="toc-text">@Controller</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RestController"><span class="toc-number">4.2.2.</span> <span class="toc-text">@RestController</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#ResponseBody"><span class="toc-number">4.2.3.</span> <span class="toc-text">@ResponseBody</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestMapping"><span class="toc-number">4.2.4.</span> <span class="toc-text">@RequestMapping</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#PathVariable"><span class="toc-number">4.2.5.</span> <span class="toc-text">@PathVariable</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestParam"><span class="toc-number">4.2.6.</span> <span class="toc-text">@RequestParam</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestBody"><span class="toc-number">4.2.7.</span> <span class="toc-text">@RequestBody</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#RequestHeader"><span class="toc-number">4.2.8.</span> <span class="toc-text">@RequestHeader</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91%E3%80%90-%E3%80%91"><span class="toc-number">5.</span> <span class="toc-text">注解开发【*】</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81web-xml-1"><span class="toc-number">5.1.</span> <span class="toc-text">1、web.xml</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81springmvc-servlet-%E9%85%8D%E7%BD%AE"><span class="toc-number">5.2.</span> <span class="toc-text">2、springmvc-servlet 配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E5%88%9B%E5%BB%BA%E5%88%B6%E7%B1%BB"><span class="toc-number">5.3.</span> <span class="toc-text">3、创建制类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4%E3%80%81%E5%89%8D%E7%AB%AF%E8%A7%86%E5%9B%BE"><span class="toc-number">5.4.</span> <span class="toc-text">4、前端视图</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Controller-1"><span class="toc-number">6.</span> <span class="toc-text">Controller</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E5%AE%9E%E7%8E%B0Controller%E6%8E%A5%E5%8F%A3%E3%80%90%E9%9D%9E%E6%B3%A8%E8%A7%A3%E3%80%91"><span class="toc-number">6.1.</span> <span class="toc-text">1、实现Controller接口【非注解】</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81-Controller%E3%80%90%E6%B3%A8%E8%A7%A3%E3%80%91"><span class="toc-number">6.2.</span> <span class="toc-text">2、@Controller【注解】</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Controller-2"><span class="toc-number">6.2.1.</span> <span class="toc-text">@Controller</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81-RequestMapping"><span class="toc-number">6.3.</span> <span class="toc-text">3、@RequestMapping</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Restful%E9%A3%8E%E6%A0%BC"><span class="toc-number">7.</span> <span class="toc-text">Restful风格</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#PathVariable-1"><span class="toc-number">7.1.</span> <span class="toc-text">@PathVariable</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BB%93%E6%9E%9C%E8%B7%B3%E8%BD%AC%E6%96%B9%E5%BC%8F"><span class="toc-number">8.</span> <span class="toc-text">结果跳转方式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E7%94%9FServletAPI"><span class="toc-number">8.1.</span> <span class="toc-text">原生ServletAPI</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86"><span class="toc-number">9.</span> <span class="toc-text">数据处理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A5%E6%94%B6%E6%95%B0%E6%8D%AE"><span class="toc-number">9.1.</span> <span class="toc-text">接收数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E6%8D%AE%E6%98%BE%E7%A4%BA%E5%88%B0%E5%89%8D%E7%AB%AF"><span class="toc-number">9.2.</span> <span class="toc-text">数据显示到前端</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E6%AF%94"><span class="toc-number">9.3.</span> <span class="toc-text">对比</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B9%B1%E7%A0%81%E9%97%AE%E9%A2%98"><span class="toc-number">10.</span> <span class="toc-text">乱码问题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JSON"><span class="toc-number">11.</span> <span class="toc-text">JSON</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Jackson"><span class="toc-number">11.1.</span> <span class="toc-text">Jackson</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%AF%BC%E5%85%A5%E4%BE%9D%E8%B5%96"><span class="toc-number">11.1.1.</span> <span class="toc-text">1、导入依赖</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%B9%B1%E7%A0%81%E8%A7%A3%E5%86%B3"><span class="toc-number">11.1.2.</span> <span class="toc-text">2、乱码解决</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E6%B5%8B%E8%AF%95"><span class="toc-number">11.1.3.</span> <span class="toc-text">3、测试</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E2%80%93%E8%BD%AC%E4%B8%BAJson"><span class="toc-number">11.2.</span> <span class="toc-text">对象–转为Json</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%A4%8D%E7%94%A8%E2%80%93%E6%8A%BD%E5%8F%96%E4%B8%BA%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">11.3.</span> <span class="toc-text">代码复用–抽取为工具类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%97%E8%A1%A8%E2%80%93%E8%BD%AC%E4%B8%BAJson"><span class="toc-number">11.4.</span> <span class="toc-text">列表–转为Json</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%97%B6%E9%97%B4Date%E2%80%93%E8%BD%AC%E4%B8%BAJson"><span class="toc-number">11.5.</span> <span class="toc-text">时间Date–转为Json</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#FastJson"><span class="toc-number">11.6.</span> <span class="toc-text">FastJson</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#HttpClient"><span class="toc-number">12.</span> <span class="toc-text">HttpClient</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96-1"><span class="toc-number">12.1.</span> <span class="toc-text">依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Get%E6%96%B9%E5%BC%8F"><span class="toc-number">12.2.</span> <span class="toc-text">Get方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Post%E6%96%B9%E5%BC%8F"><span class="toc-number">12.3.</span> <span class="toc-text">Post方式</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-number">13.</span> <span class="toc-text">拦截器</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%8B%A6%E6%88%AA%E7%B1%BB"><span class="toc-number">13.1.</span> <span class="toc-text">1、自定义拦截类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E9%85%8D%E7%BD%AE%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="toc-number">13.2.</span> <span class="toc-text">2、配置拦截器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#spring-mvc-xml"><span class="toc-number">13.3.</span> <span class="toc-text">spring-mvc.xml</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E5%B8%B8%E7%94%A8%E3%80%90%E7%99%BB%E5%BD%95%E5%88%A4%E6%96%AD%E6%8B%A6%E6%88%AA%E3%80%91"><span class="toc-number">13.4.</span> <span class="toc-text">3、常用【登录判断拦截】</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="toc-number">14.</span> <span class="toc-text">文件上传</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%E3%80%81%E4%BE%9D%E8%B5%96"><span class="toc-number">14.1.</span> <span class="toc-text">1、依赖</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2%E3%80%81%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E9%85%8D%E7%BD%AE"><span class="toc-number">14.2.</span> <span class="toc-text">2、文件上传配置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3%E3%80%81%E4%BB%A3%E7%A0%81"><span class="toc-number">14.3.</span> <span class="toc-text">3、代码</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD"><span class="toc-number">15.</span> <span class="toc-text">文件下载</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javaall.gif" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java八股文"/></a><div class="content"><a class="title" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文">Java八股文</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javahd.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java后端"/></a><div class="content"><a class="title" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端">Java后端</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/06/02/MybatisPlus/" title="MybatisPlus"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MybatisPlus"/></a><div class="content"><a class="title" href="/2023/06/02/MybatisPlus/" title="MybatisPlus">MybatisPlus</a><time datetime="2023-06-02T14:22:22.000Z" title="发表于 2023-06-02 22:22:22">2023-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Linux/" title="Linux"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Linux.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Linux"/></a><div class="content"><a class="title" href="/2023/05/05/Linux/" title="Linux">Linux</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Redis/" title="Redis"><img src= "" data-lazy-src="/img/loading.gif" data-original="ttps://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Redis.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis"/></a><div class="content"><a class="title" href="/2023/05/05/Redis/" title="Redis">Redis</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 辰</div><div class="framework-info"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn">粤ICP备2023096650号</a><span class="footer-separator">|</span><a target="_blank" rel="noopener" href="http://hchen.cloud">hchen.cloud</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body></html>